package com.bigfire.dtm.core.event.repository.user;

import com.bigfire.dtm.dal.entity.user.QUserInfoEntry;
import com.bigfire.dtm.dal.entity.user.UserInfoEntry;
import com.bigfire.dtm.dal.entity.user.UserInfoRepository;
import com.bigfire.dtm.shared.enums.YesNoEnum;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.List;

/**
 * 查询用户相关数据
 * @author Damon S.
 * @version v1.0.1
 * @date 2019年11月22日 14:55
 */
@Slf4j
@Component
public class UserDataHandler {

    private final JPAQueryFactory userQueryFactory;
    private final QUserInfoEntry qUserInfoEntry;
    private final UserInfoRepository userInfoRepository;


    public UserDataHandler(/*@Qualifier("EntityManager")*/EntityManager entityManager,UserInfoRepository userInfoRepository) {
        this.userQueryFactory = new JPAQueryFactory(entityManager);
        this.qUserInfoEntry = QUserInfoEntry.userInfoEntry;
        this.userInfoRepository=userInfoRepository;
    }

    public List<UserInfoEntry> findUserByTenantId(Long tenantId) {
        return userQueryFactory.selectFrom(qUserInfoEntry)
                .where(qUserInfoEntry.tenantId.eq(tenantId)
                        .and(qUserInfoEntry.removed.eq(YesNoEnum.N.getCode())))
                .fetch();
    }

    @Transactional
    public UserInfoEntry findUserById(Long userId) {
        userQueryFactory.update(qUserInfoEntry).set(qUserInfoEntry.userId,1L).where(qUserInfoEntry.userId.eq(userId)).execute();
        //userQueryFactory.delete();

        UserInfoEntry a = UserInfoEntry.builder().username("test").userId(2L).build();
        userInfoRepository.save(a);

        return userQueryFactory.selectFrom(qUserInfoEntry)
                .where(qUserInfoEntry.userId.eq(userId)
                        .and(qUserInfoEntry.removed.eq(YesNoEnum.N.getCode())))
                .fetchOne();
    }

    public List<UserInfoEntry> findUserByIds(Collection<Long> userIds) {
        return userQueryFactory.selectFrom(qUserInfoEntry)
                .where(qUserInfoEntry.userId.in(userIds)
                        .and(qUserInfoEntry.removed.eq(YesNoEnum.N.getCode())))
                .fetch();
    }
}
